import Imagelocation from '@/components/Imagelocation';
import DefaultNavBar from '@/components/StandNavBar/DefaultNavBar';
import cartPng from '@/giftCardSubPack/images/coupon/cart.png';
import utils from '@/utils';
import { debounce } from '@/utils/helper.js';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import { Image, ScrollView, Text, View } from '@tarojs/components';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import classNames from 'classnames';
import React, { useCallback, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { checkProductIsSoldOut } from '@/dataTransfer/product';

import pSoldOut from '../images/activity/sold-out.png';
import pStarDown from '../images/activity/star-down.png';
import pStarUp from '../images/activity/star-up.png';
import ImgCover from './imgCover';
import './index.scss';

const StoreType = {
  // 同城外卖
  takeaway: 'takeaway',

  // 线上商城
  store: 'store',
};

const StoreInfo = ({ store }) => {
  return (
    <View className="store-info">
      <Imagelocation className="logo" src={store?.logo} type="shop" />

      <View className="store-right">
        <View className="store-name">{store?.name}</View>

        <View className="store-star">
          <View className="txt">{store?.grade}</View>
          <View className="start">
            <View className="backL">
              <Image className="sIcon" src={pStarDown} />
            </View>
            <View className="faceL" style={{ width: (store?.grade * 100) / 5 + '%' }}>
              <Image className="sIcon" src={pStarUp} />
            </View>
          </View>

          <View className="comment">{store?.scoreCountdto?.count ?? '0'}条评价</View>
        </View>
      </View>
    </View>
  );
};

const OffProductItem = ({
  item: { title, price, originalPrice, url, optionValue = '', stock },
  item,
  addProduct,
}) => {
  const isSoldOut = checkProductIsSoldOut(stock);

  return (
    <View className="product">
      <View className="left">
        <Imagelocation className="product-img" src={url} />

        {isSoldOut && <ImgCover txt="已售罄" />}
      </View>
      <View className="off-right">
        <View className="name">{title}</View>

        <View className="intro">{optionValue}</View>

        <View className="origin-price">
          <View className="prefix">原价</View>

          <View className="price">¥{originalPrice}</View>
        </View>

        <View className="off-price">
          <View className="tag customePageBorderStyle">
            <View className="txt customePageStyle">折扣价</View>
          </View>

          <View className="unit">¥</View>
          <View className="price">{price}</View>
        </View>

        <View
          className={classNames('buy-now customePageBackgroundStyle', { 'sold-out': isSoldOut })}
        >
          <View
            className="txt"
            onClick={() => {
              !isSoldOut && addProduct(item);
            }}
          >
            {isSoldOut ? '已售罄' : '马上抢'}
          </View>
        </View>
      </View>
    </View>
  );
};

const RebateProductItem = ({
  item: { title, price, url, optionValue = '', stock },
  item,
  reduceText,
  addProduct,
}) => {
  const tags = reduceText.split(',');

  const thePrice = parseFloat(price).toFixed(2);

  const isSoldOut = checkProductIsSoldOut(stock);

  return (
    <View className="product">
      <View className="left">
        <Imagelocation className="product-img" src={url} />

        {isSoldOut && <ImgCover txt="已售罄" />}
      </View>
      <View className="right">
        <View className="info">
          <View className="name">{title}</View>
          <View className="intro">{optionValue}</View>
          <View className="pricePay">
            <View className="realPrice">
              <Text className="unit">￥</Text>
              <Text className="num">{thePrice}</Text>
            </View>
            {/* <View className="saleNum">{quantity ?? 0}人付款</View> */}
          </View>
          <View className="coupInfo">
            {tags.map((v) => {
              return (
                <View key={v} className="infoBtn customePageStyleBg15">
                  <View className="txt customePageStyle">{v}</View>
                </View>
              );
            })}
          </View>
          {!isSoldOut ? (
            <Image
              src={cartPng}
              className="add"
              onClick={() => {
                addProduct(item);
              }}
            />
          ) : (
            <Image src={pSoldOut} className="sold-out" />
          )}
        </View>
      </View>
    </View>
  );
};

const ActivityProducts = ({
  dispatch,
  loading,
  activityProductList,
  activityProductListFinished,
  activityProductAmt,
  shopBaseInfo,
}) => {
  useShowLoading(loading, ['giftCard/fetchActivityProductList']);

  const { params: { id, isRebate, merchantId, orgId, reduces, productSource } = {} } = useRouter();

  const reduceText = decodeURIComponent(reduces ?? '');

  const storeType = productSource === '1' ? StoreType.store : StoreType.takeaway;

  // 满减提示的高度
  const [height, setHeight] = useState(0);
  // 头部高度
  const [topMenuHeight, setTopMenuHeight] = useState(0);

  // 满减时, 显示的 剩余多少元满足满减
  const [restAmount, setRestAmount] = useState({
    current: 0,
    rest: 0,
  });

  // 获取 商品列表
  const getNextList = useCallback(
    (params) => {
      return dispatch({
        type: 'giftCard/fetchActivityProductList',
        payload: { pageSize: 10, id, ...params },
      });
    },
    [id],
  );

  // 滚动获取
  const handleScrollToLower = debounce(() => {
    !activityProductListFinished && activityProductList?.length > 0 && getNextList();
  }, 1200);

  // 获取 商品列表
  useEffect(() => {
    getNextList({ page: 1 });
  }, [id]);

  // 获取在购物车中的适合这次优惠券的商品总价
  // 每次页面显示时重新获取
  useDidShow(() => {
    if (!utils.getToken()) {
      return;
    }

    dispatch({
      type: 'giftCard/getActivityProductAmt',
      payload: id,
    });
  });

  // 获取店铺信息
  useEffect(() => {
    dispatch({
      type: 'otherApi/getLocalOrgDetail',
      payload: {
        orgId,
        appId: storeType === StoreType.store ? 'thjs_shop_org' : 'thjs_takeout_org',
      },
    });
  }, [orgId]);

  // 满减时显示的价格
  useEffect(() => {
    setRestAmount({
      current: activityProductAmt?.total ?? 0,
      rest: activityProductAmt?.fullAmount ?? 0,
    });
  }, [activityProductAmt]);

  useEffect(() => {
    setTimeout(() => {
      // 获取满减提示高度
      Taro.createSelectorQuery()
        .select('.activity-info')
        .boundingClientRect()
        .exec(([v]) => {
          setHeight(v?.height ?? 0);
        });

      // 获取顶部高度
      Taro.createSelectorQuery()
        .select('.nav-bar-wrap')
        .boundingClientRect()
        .exec(([v]) => {
          setTopMenuHeight(v?.height ?? 0);
        });
    });
  }, []);

  // 加入购物车
  const addProduct = debounce(async (product) => {
    const { productReleaseId, productReleaseVariantId, favouredId, favouredType, type, price } =
      product;

    // 加入购物车
    const res = await dispatch({
      type: 'productList/addProduct',
      payload: {
        productReleaseId,
        productVariantReleaseId: productReleaseVariantId,
        orgId,
        merchantId,
        favouredId,
        favouredType,
        type,
        num: 1,
      },
    });

    // 计算满减价格
    setRestAmount({
      current: restAmount.current + price,
      rest: restAmount.rest - price,
    });

    // 计算满减剩余价格
    if (isRebate) {
      await dispatch({
        type: 'giftCard/addActivityProductSumPrice',
        payload: product.price,
      });
    }

    if (res.code === '1') {
      Taro.showToast({
        title: '加入购物车成功',
        icon: 'none',
      });
    }
  }, 1000);

  return (
    <>
      <DefaultNavBar title={isRebate ? '满减活动' : '折扣活动'} className="nav-bar-wrap" />
      <View
        className="ActivityProducts"
        style={{
          height: utils.getCalcHeight({}, topMenuHeight + 'px'),
        }}
      >
        <View className="products-top">
          <StoreInfo store={shopBaseInfo} />
        </View>

        {isRebate && <View className="activity-info">限时促销：{reduceText}</View>}

        <ScrollView
          className="product-products"
          scrollY
          style={{
            height: utils.getCalcHeight(
              {},
              topMenuHeight + 'px',
              // 门店信息
              161,
              // 底部加入购物车高度
              120,
              // 满减提示的高度, 已经是计算过了的
              height + 'px',
              // 满减的上边距和下边距
              20,
              20,
            ),
          }}
          onScrollToLower={handleScrollToLower}
        >
          {activityProductList?.map((item) => {
            const EleTag = isRebate ? RebateProductItem : OffProductItem;

            return (
              <EleTag
                key={item.productReleaseId + '|' + item.productReleaseVariantId}
                item={item}
                reduceText={reduceText}
                addProduct={addProduct}
              ></EleTag>
            );
          })}

          {activityProductListFinished && activityProductList?.length > 8 && (
            <View className="end">- 我是有底线的 -</View>
          )}
        </ScrollView>

        <View className="bottom-info">
          <View className="left">
            <View className="summary-wrap">
              {!isRebate && <View className="summary-prefix">合计</View>}

              <View className="summary">￥{parseFloat(restAmount.current).toFixed(2)}</View>
            </View>

            {isRebate && restAmount.rest > 0 && (
              <View className="info">
                再买
                <Text className="num">{parseFloat(restAmount.rest).toFixed(2)}</Text>
                元可享受优惠
              </View>
            )}
          </View>
          <View
            className="right customePageBackgroundStyle"
            onClick={() => {
              Taro.navigateTo({ url: '/pages/mainPages/cartSin/index' });
            }}
          >
            <View className="txt">去购物车</View>
          </View>
        </View>
      </View>
    </>
  );
};
export default connect(({ loading, giftCard, otherApi }) => ({
  loading,
  activityProductList: giftCard.activityProductList,
  activityProductListFinished: giftCard.activityProductListFinished,
  activityProductAmt: giftCard.activityProductAmt,
  shopBaseInfo: otherApi.shopBaseInfo,
}))(ActivityProducts);
